package hikari.persistence.propertieseditor.editors;

import com.gooddies.texteditors.DefaultTextField;
import com.gooddies.texteditors.validation.AbstractValidator;
import hikari.persistence.file.FileSection;
import java.io.IOException;
import javax.swing.JComponent;

/**
 * @author sad
 */
public class StringPropertyEditor extends DefaultTextField implements IPropertyEditor{

    @Override
    public Object getEditorValue() {
        return getText();
    }

    @Override
    public void setEditorValue(Object value) {
        setText((String)value);
    }

    @Override
    public void setMax(Object max) {
        throw new UnsupportedOperationException("String property editor does not support max property");
    }

    @Override
    public void setMin(Object min) {
        throw new UnsupportedOperationException("String property editor does not support min property");
    }

    @Override
    public void setValidator(AbstractValidator validator) {
        addValidator(validator);
    }

    @Override
    public void setMaxLength(String length) {
        int tMaxLength = Integer.parseInt((String) length);
        setMaxTextLength(tMaxLength);
    }

    @Override
    public JComponent getJComponent() {
        return this;
    }

    @Override
    public void save(String fieldName, FileSection section) throws IOException {
        section.writeString(fieldName, (String) getEditorValue());
    }

    @Override
    public void read(String fieldName, FileSection section) throws IOException {
        String value = section.readString(section.getChunk(fieldName));
        setEditorValue(value);
    }
}
